import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {Util} from "../../../common/util";
import {InterbankService} from "../interbank.service";
import {IBTListColumnDisplayConfigModel, ListComponent} from "../list/list.component";
import * as _ from "lodash";
import * as queryString from "query-string";
import {Subscription} from "rxjs/Subscription";
import {PaginationModel} from "../../../widgets/pagination/pagination.component";
import {Observable} from "rxjs/Observable";
import {environment} from "environments/environment";

export interface IBTHistorySearchModel {
  /**
   * 组合名称
   */
  ownHolderShortName?: string;
  /**
   * 组合代码
   */
  ownHolderAccount?: string;
  /**
   * 交易对手
   */
  direction?: string ;
  /**
   * 交易日期
   */
  tradeDate?: string ;
  /**
   * 结算日期
   */
  settlementDate?: string ;
  /**
   * 业务类型
   */
  tradeType?: string;
}

/**
 * 银行间----历史交易组件
 */
@Component({
  selector: 'interbank-history',
  templateUrl: './history.component.html',
  styleUrls: ['./history.component.scss']
})
export class HistoryComponent implements OnInit, AfterViewInit {

  /**
   * 历史交易列表数据对象
   * @type {{list: Array}}
   */
  public data: any = {list: []};

  /**
   * 列表序号偏移量
   * @type {number}
   */
  public indexOffest = 0;

  /**
   * 当前分页信息
   */
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  /**
   * 列表配置
   * @type {{color: boolean; file: boolean; select: boolean}}
   */
  public listConfig: IBTListColumnDisplayConfigModel = {
    color: false,
    file: true,
    unableUpload: true,
    unableRemoveFile: true,
    select: false,
    urgentStatus: false,
    trdFundName: false,
    trdTradeType: false,
    trdProductCode: false,
    trdProductName: false,
    trdSettleBalance: false,
    trdPledgeMatchStatus: false
  };

  @ViewChild(ListComponent)
  public listComponent: ListComponent;

  constructor(public service: InterbankService) {
  }

  ngOnInit() {
    this.search();
  }

  ngAfterViewInit(): void {
    Util.daterangepickerPluginInit(".daterangepicker-plugin");
    Util.$(this.listComponent.fixedTable.nativeElement).css('background', 'white');
    this.select2PluginInit().then(() => {
      this.search();
    });
  }

  /**
   * 初始化select2插件搜索下拉框
   */
  public async select2PluginInit() {
    await new Promise((resolve, reject) => {
      this.service.getFundInfoListData().subscribe((data) => {
        data = (data || []).map((item) => {
          return {
            id: item.fundCode,
            text: item.fundName
          };
        });
        const $fundCodeList = Util.$('#fundCodeList').select2({
          data,
          multiple: true,
          closeOnSelect: false
        });
        $fundCodeList.data('select2').$container.css('width', '154px');
        resolve(data);
      });
    });
    await new Promise((resolve, reject) => {
      this.service.getOppoHolderAccountListData().subscribe((data) => {
        data = (data || []).map((item) => {
          return {
            id: item.account,
            text: item.shortName
          };
        });
       const $oppoHolderAccountList = Util.$('#oppoHolderAccountList').select2({
          data,
          multiple: true,
          closeOnSelect: false
        });
       $oppoHolderAccountList.data('select2').$container.css('width', '154px');
        resolve(data);
      });
    });
    await new Promise((resolve, reject) => {
      this.service.getFundFavoriteTagIdList().subscribe((data) => {
        if (data && Array.isArray(data.list) && data.list.length > 0) {
          data = data.list.map((item) => {
            return {
              id: item.objid,
              text: item.objname
            };
          });
        } else {
          data = [];
        }
        const $fundFavoriteTagIdList = Util.$('#fundFavoriteTagIdList').select2({
          data,
          multiple: true,
          closeOnSelect: false
        });
        $fundFavoriteTagIdList.data('select2').$container.css('width', '154px');
        resolve(data);
      });
    });
  }

  /**
   * 获取银行间债券历史交易列表数据并渲染列表
   * @returns {Subscription}
   */
  public search(): Subscription {
    return this.getListData(this.wrapperSearchModule());
  }

  /**
   * 将所有搜索条件框重置为空
   */
  public resetSearch() {
    Util.resetInputs('.ibt-search-input');
  }

  /**
   * 导出银行间债券交易列表数据
   */
  public exportData() {
    const search = this.wrapperSearchModule();
    search['token'] = sessionStorage.getItem('username');
    const queryParamStr = queryString.stringify(search);
    const url = environment.server + 'otc/v1/chinamoney/bond-trade-groupview-export' + '?' + queryParamStr;
    const link: HTMLAnchorElement = window.document.createElement('a');
    link.href = url;
    link.setAttribute('download', '');
    link.click();
    window.URL.revokeObjectURL(link.href);
    link.remove();
  }

  /**
   * 将用户输入所有搜索值包装成为一个搜索数据模型对象
   * @returns {IBTHistorySearchModel}
   */
  public wrapperSearchModule(): IBTHistorySearchModel {
    const $ = window["$"];
    const data: IBTHistorySearchModel = {};
    $(".ibt-search-input").each((index, item) => {
      const $item = Util.$(item);
      const type = item.type;
      const id = item.id;
      const value = item.value;
      const select2 = $item.data('select2');
      const daterangepicker = $item.data('daterangepicker');
      if (id && id !== "") {
        if (select2 != null) {
          data[id] = $item.select2('val');
        } else if (daterangepicker != null) {
          data[`${id}Begin`] = (value != null && value.length > 0 ) ? daterangepicker.startDate.format('YYYYMMDD') : "";
          data[`${id}End`] = (value != null && value.length > 0 ) ? daterangepicker.endDate.format('YYYYMMDD') : "";
        } else {
          if (type === 'text' || type === 'select' || type === 'select-one') {
            data[id] = value;
          } else if (type === 'checkbox') {
            data[id] = item.checked ? value : "";
          }
        }
      }
    });
    return data;
  }

  /**
   * 获取银行间债券交易列表数据
   * @param search
   * @returns {Observable<any>}
   */
  public getListData(search: IBTHistorySearchModel,
                     currentPageNum: number = this.pageInfo.currentPageNum,
                     pageSize: number = this.pageInfo.pageSize) {
    return this.service.getHisttoryListData(search, currentPageNum, pageSize).subscribe((result) => {
      if (result != null && result.data != null && result.data.list != null) {
        this.data.list = result.data.list;
        this.pageInfo.totalPages = result.data.pages;
        this.pageInfo.total = result.data.total;
        this.pageInfo.startRow = result.data.startRow;
        this.pageInfo.endRow = result.data.endRow;
        this.indexOffest = (this.pageInfo.currentPageNum - 1) * this.pageInfo.pageSize;
      }
    });
  }

  /**
   * 根据页码请求查询相关基金配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param currentPageNum
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.getListData(
      this.wrapperSearchModule(),
      this.pageInfo.currentPageNum,
      this.pageInfo.pageSize);
  }

  /**
   * 改变每页显示记录数
   * @param pageSize
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.getListData(this.wrapperSearchModule(), 1, this.pageInfo.pageSize);
    }
  }
}
